<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/8/21
 * Time: 11:35
 */

namespace app\common\utils;


use OSS\OssClient;
use think\Exception;
use think\Log;

class OssUtil
{
    private static $ossClient = null;
    private static $ossClientInternal = null;
    private static $ossBucket = null;

    /**
     * @return OssClient
     */
    public static function getClient() : OssClient
    {
        if (empty(self::$ossClient)) {
            self::$ossClient = new OssClient(
                config('aliYunOSS.AccessKeyId'),
                config('aliYunOSS.AccessKeySecret'),
                config('aliYunOSS.EndPoint')
            );
        }
        return self::$ossClient;
    }

    /**
     * @return OssClient
     */
    public static function getClientInternal() : OssClient
    {
        if (empty(self::$ossClientInternal)) {
            self::$ossClientInternal = new OssClient(
                config('aliYunOSS.AccessKeyId'),
                config('aliYunOSS.AccessKeySecret'),
                config('aliYunOSS.ServerOut') ?
                config('aliYunOSS.EndPoint') :
                config('aliYunOSS.EndPointInternal')
            );
        }
        return self::$ossClientInternal;
    }

    /**
     * @return null
     */
    public static function getOssBucket()
    {
        if (empty(self::$ossBucket)) {
            self::$ossBucket = config('aliYunOSS.Bucket');
        }
        return self::$ossBucket;
    }

    /**
     * @param $object
     * @param $file
     * @return mixed|false
     */
    public static function put($object, $file) {
        $client = self::getClientInternal();

        $client->uploadFile(self::getOssBucket(), $object, $file);
        return self::DNS_HOST.'/'.$object;
    }

    /**
     * 删除url指向的文件
     *
     * @param $url
     * @return mixed
     */
    public static function delete($url) {

        if (false == config('aliYunOSS.EnableDelete')) return true;

        $client = self::getClient();

        $re = parse_url($url);
        if (empty($re['host']) || empty($re['path'])) return false;
        $bucket = config('aliYunOSS.Bucket');
        $object = substr($re['path'],1);

        try{
            $re = $client->deleteObject($bucket, $object);
            return $re;
        }catch (\Exception $ex){
            Log::error($ex->getMessage());
            return false;
        }

    }

    /**
     * url签名，当bucket设置为私有时需要签名才能访问
     * 由于视频需要付费观看，所以加上限制
     *
     * @param string $url object的url地址
     * @param int $duration 有效期长度(秒)
     * @return string 已签名的url
     */
    public static function signatureUrl($url, $duration = 30){

        $ak = config('aliYunOSS.AccessKeyId');
        $sk = config('aliYunOSS.AccessKeySecret');

        $components = parse_url($url);
        $bucket = substr($components['host'],0, strpos($components['host'],'.'));

        $expire = time() + ceil($duration) + 5;
        $StringToSign="GET\n\n\n".$expire."\n/".$bucket."/".$components['path'];
        $Sign=base64_encode(hash_hmac("sha1",$StringToSign, $sk,true));

        $url = $url."?OSSAccessKeyId=$ak&Expires=$expire&Signature=".urlencode($Sign);

        return $url;
    }

    const DNS_HOST = 'http://image.cloud.51taojingu.com';
    /**
     * 将地址修改为dns地址
     * @param $url
     * @return string
     */
    public static function makeDNSUrl($url) {
        $path = parse_url($url,PHP_URL_PATH);
        if ($path[0] != '/') $path = '/' . $path;
        return $path ? self::DNS_HOST.$path : '';
    }

}